<?php

namespace Drupal\shusy_store_order\Entity;

use Drupal\shusy_store_order\ViewsController\Traits\ShusyStoreOrderStatusTrait;
use Drupal\shusy_store_order_line\Entity\ShusyStoreOrderLine;
use Entity;

class ShusyStoreOrder extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $type = 0;

  public $store_id;

  public $amount = 0;

  public $total = 0;

  public $status;

  public $upTotal = FALSE;

  use ShusyStoreOrderStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_store_order');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }
    //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
    //未提交时允许计算价格
    if (in_array($this->status, [2, 7]) || $this->upTotal) {
      //计算订单总价
      $this->total = 0;
      $this->amount = 0;
      $lines = $this->lines();
      foreach ($lines as $line) {
        if ($line instanceof ShusyStoreOrderLine && $line->status == 1) {
          $this->total += $line->total;
          if ($line->type == 'product') {
            $this->amount += $line->total;
          }
        }
      }
    }
    return parent::save();
  }

  function lines() {
    $es = shusy_store_order_line_load_multiple(FALSE, [
      'store_order_id' => $this->id,
      'status' => 1,
    ]);
    return $es;
  }

  function products() {
    $es = shusy_store_order_line_load_multiple(FALSE, [
      'store_order_id' => $this->id,
      'type' => 'product',
      'status' => 1,
    ]);
    return $es;
  }
}
